package org.example.util;

import org.example.bean.Cord;
import org.example.bean.GameHashMap;
import org.example.bean.GameMap;
import org.example.bean.Polygon;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc:
 * @Author: yanghongjun
 * @Date: 2024/5/21
 **/
public class PolygonUtil {
    private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    /**
     * 从给定的地图数据中找出所有阻挡多边形。
     *
     * @param maps 二维整数数组表示的地图，1表示阻挡，0表示非阻挡。
     * @return 包含所有阻挡多边形的列表。
     */
    public static List<Polygon> findPolygons(int[][] maps) {
        List<Polygon> polygons = new ArrayList<>();
        if (maps == null || maps.length == 0 || maps[0].length == 0) {
            return polygons;
        }

        int width = maps.length;
        int height = maps[0].length;
        boolean[][] visited = new boolean[width][height];

        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (maps[i][j] == 1 && !visited[i][j]) {
                    Polygon polygon = new Polygon();
                    dfs(maps, i, j, visited, polygon);
                    if (!polygon.getList().isEmpty()) {
                        polygons.add(polygon);
                    }
                }
            }
        }
        return polygons;
    }

    private static void dfs(int[][] maps, int x, int y, boolean[][] visited, Polygon polygon) {
        visited[x][y] = true;

        // 检查是否是边界点（至少有一个相邻格子是非阻挡的或越界）
        boolean isBoundary = false;
        for (int[] direction : DIRECTIONS) {
            int nx = x + direction[0];
            int ny = y + direction[1];
            if (nx < 0 || nx >= maps.length || ny < 0 || ny >= maps[0].length || maps[nx][ny] != 1) {
                isBoundary = true;
                break;
            }
        }

        // 如果是边界点，则添加到多边形中
        if (isBoundary) {
            polygon.addCord(new Cord(x, y));
        }

        // 继续DFS搜索相邻的阻挡格子
        for (int[] direction : DIRECTIONS) {
            int nx = x + direction[0];
            int ny = y + direction[1];
            if (nx >= 0 && nx < maps.length && ny >= 0 && ny < maps[0].length && maps[nx][ny] == 1 && !visited[nx][ny]) {
                dfs(maps, nx, ny, visited, polygon);
            }
        }
    }
}
